package rsa;

import cn.hutool.crypto.asymmetric.AsymmetricCrypto;
import cn.hutool.crypto.asymmetric.KeyType;
import sun.misc.BASE64Decoder;

import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @description: TODO
 * @author admin
 * @date 2024/4/22 10:05
 * @version 1.0
 */
public class RsaUtil {
    public static void main(String[] args) throws Exception {
//        AsymmetricCrypto asymmetricCrypto = new AsymmetricCrypto("RSA");
//        System.out.println(asymmetricCrypto.getPrivateKeyBase64());
//        System.out.println(asymmetricCrypto.getPublicKeyBase64());

        String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJW23GPZ5BU+F5ECMW01TBQLFFaUcs4O0emoEmGSuryo4beT3xvtgEeKVuXNgKRaZbE7P19pw5YDK5eON3WMiWpK8SXiWnDYvPLtqCrN677Q/gzPgztHsvT6Z9tm4Tm3M4Kbg8f11z9P3ZIMCkMCHx6RVmCMJGnO/EHO0X2Xs1VDAgMBAAECgYAsNUru0TBgdW1QDG276bkFUiA3UK512jpx3IdQ+JrbiqLcKnX/MSpn9ZmjUgNihK7ynqQf8IMokNcWcZA+zbjljKKcOd+309bxsPwZ+4h+j2fpVEbFUhg1Mj5P7LsniMt8rDDOHMv9lQWkKdLocYvXg+t0tPLCnQX9oGJLq8/agQJBAOrPrEHBSN32HPtnYduh6yI+xRkgEcs6VCueiuCEKYr9+lM2ZZu1CWj2MAdQG/48OAefL6dodGySu/+yQnrG5LsCQQCjOWGLfHQ8MfeZzzD7JS6yXZcib/I7a02YBsW+M09n9mLSwoGacyNeV4u43DMFT622BMFYM1bbDJHlIqtsJI0ZAkBy0DrNKCJmDcpcD0/lIcYkR4b+YxTwR0QS1AHaCCV8BfXZrFaAjUPdo8sWOFCHvpAzAd4+QC/1SsZMH7Cr8gazAkEAmn4CbPNEVYF5+VRZ6Sy9cUgSeB77aPBchkvKuQd53k4gJZrC7zyRuockkbmidSGAqyr/Egut5zGTmgzhsj86aQJBAMEXco3Y9SfGgInPY5Ladyxzce2BRxZE4N+ILvlJ2JIAHFpZVp97KHkiaCW3op+wWLQHVIWgy0DQ9JvgMqE3ltA=";
        String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCVttxj2eQVPheRAjFtNUwUCxRWlHLODtHpqBJhkrq8qOG3k98b7YBHilblzYCkWmWxOz9facOWAyuXjjd1jIlqSvEl4lpw2Lzy7agqzeu+0P4Mz4M7R7L0+mfbZuE5tzOCm4PH9dc/T92SDApDAh8ekVZgjCRpzvxBztF9l7NVQwIDAQAB";
        String json = "{\n" +
                "  \"deviceCode\": \"test_099c19c10b99\",\n" +
                "  \"deviceModel\": \"test_756076ccdabd\",\n" +
                "  \"deviceAddr\": \"test_362eef2ab3e1\",\n" +
                "  \"hospitalId\": \"510410\",\n" +
                "  \"hospitalName\": \"四川省人民医院\",\n" +
                "  \"courtyard\": \"test_c594ff101a24\",\n" +
                "  \"errorCode\": \"001001\",\n" +
                "  \"errorName\": \"读卡器故障\",\n" +
                "  \"state\": 32,\n" +
                "  \"remark\": \"test_d3eb375ca4db\",\n" +
                "  \"createBy\": \"test_3733e534f17e\",\n" +
                "  \"createTime\": \"2020-04-23 07:45:47\",\n" +
                "}";


        AsymmetricCrypto rsa = new AsymmetricCrypto("RSA", privateKey, null);
        String encryptBase64 = rsa.encryptBase64(json, KeyType.PrivateKey);
        System.out.println(encryptBase64);

        AsymmetricCrypto rsa1 = new AsymmetricCrypto("RSA", null, publicKey);
        String decryptStr = rsa1.decryptStr(encryptBase64, KeyType.PublicKey);
        System.out.println(decryptStr);

//        RSA rsa = new RSA();
//        //获得私钥
//        rsa.getPrivateKey();
//        String privateKeyBase64 = rsa.getPrivateKeyBase64();
//        System.out.println(privateKeyBase64);
//        //获得公钥
//        rsa.getPublicKey();
//        String publicKeyBase64 = rsa.getPublicKeyBase64();
//        System.out.println(publicKeyBase64);
//
//
//        //公钥加密，私钥解密
//        byte[] encrypt = rsa.encrypt(StrUtil.bytes("我是一段测试aaaa", CharsetUtil.CHARSET_UTF_8), KeyType.PublicKey);
//        byte[] decrypt = rsa.decrypt(encrypt, KeyType.PrivateKey);
//
//        System.out.println(StrUtil.str(decrypt, CharsetUtil.CHARSET_UTF_8));
//
//        //既然是加密，那肯定是不希望别人知道我的消息，所以只有我才能解密，所以可得出公钥负责加密，私钥负责解密；
//        //既然是签名，那肯定是不希望有人冒充我发消息，只有我才能发布这个签名，所以可得出私钥负责签名，公钥负责验证
//
//
//        //私钥加签，公钥验签
//        byte[] encrypt2 = rsa.encrypt(StrUtil.bytes("我是一段测试aaaa", CharsetUtil.CHARSET_UTF_8), KeyType.PrivateKey);
//        byte[] decrypt2 = rsa.decrypt(encrypt2, KeyType.PublicKey);
//
//        //Junit单元测试
//        System.out.println(StrUtil.str(decrypt2, CharsetUtil.CHARSET_UTF_8));
//
//        //手动生成公钥私钥
////        KeyPair pair = SecureUtil.generateKeyPair("RSA");
////        PrivateKey aPrivate = pair.getPrivate();
////        PublicKey aPublic = pair.getPublic();
//
//        //私钥加签
//        AsymmetricCrypto privateAsymmetricCrypto = new AsymmetricCrypto("RSA", privateKeyBase64, null);
//        //公钥解签
//        AsymmetricCrypto publicAsymmetricCrypto = new AsymmetricCrypto("RSA", null, publicKeyBase64);
//
//        byte[] encrypt3 = privateAsymmetricCrypto.encrypt("你好呀", KeyType.PrivateKey);
//        //将byte数组转为base64 方便网络 JSON 传输
//        String encryptStr = Base64.getEncoder().encodeToString(encrypt3);
//        byte[] decode = Base64.getDecoder().decode(encryptStr);
//
//        byte[] decrypt1 = publicAsymmetricCrypto.decrypt(decode, KeyType.PublicKey);
//        System.out.println(StrUtil.str(decrypt1, CharsetUtil.CHARSET_UTF_8));

    }


    /**
     * @desc: 将字符串转换成RSAPublicKey类型
     * @date 2020-6-12 11:03:05
     * @param
     * @return
     */
    public static RSAPublicKey getRSAPublidKeyBybase64(String base64s) throws Exception {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec((new BASE64Decoder()).decodeBuffer(base64s));
        RSAPublicKey publicKey = null;
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        try {
            publicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);
        } catch (InvalidKeySpecException var4) {

        }
        return publicKey;
    }

    /**
     * @desc: 将字符串转换成RSAPrivateKey类型
     * @date 2020-6-12 11:03:01
     * @param
     * @return
     */
    public static RSAPrivateKey getRSAPrivateKeyBybase64(String base64s) throws Exception {
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec((new BASE64Decoder()).decodeBuffer(base64s));
        RSAPrivateKey privateKey = null;
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        try {
            privateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
        } catch (InvalidKeySpecException var4) {
        }
        return privateKey;
    }

}
